package me.firstapp.bts.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import me.firstapp.bts.service.TransferJobService;
import me.firstapp.common.exception.ServiceException;
import me.firstapp.common.utils.DateUtils;
import me.firstapp.module.weixin.member.Member;
import me.firstapp.module.weixin.transfer.TransferMember;
import me.firstapp.module.weixin.transfer.TransferMemberProduct;
import me.firstapp.service.weixin.member.MemberService;
import me.firstapp.service.weixin.product.ProductOrderService;
import me.firstapp.service.weixin.transfer.TransferMemberProductService;
import me.firstapp.service.weixin.transfer.TransferMemberService;

@Service
public class TransferJobServiceImpl implements TransferJobService {

	private static Logger logger = LoggerFactory.getLogger(TransferJobServiceImpl.class);

	@Autowired
	private MemberService memberService;

	@Autowired
	private TransferMemberService transferMemberService;

	@Autowired
	private ProductOrderService productOrderService;

	@Autowired
	private TransferMemberProductService transferMemberProductService;

	@Override
	public void addAndUpdateTransferMember() {
		try {
			List<Integer> memberLevelList = new ArrayList<>();
			memberLevelList.add(Member.VIP_LEVEL_BASE);
			memberLevelList.add(Member.VIP_LEVEL_FANS);
			for (int pageNo = 1; pageNo < 1000000; pageNo++) {
				List<Member> members = memberService.findMembersPage(pageNo, 100, memberLevelList);
				if (null == members || members.isEmpty()) {
					break;
				}
				for (Member member : members) {
					if (Member.VIP_LEVEL_BASE == member.getVipLevel()
							|| Member.VIP_LEVEL_FANS == member.getVipLevel()) {
						List<Member> fans = memberService.findFans(member.getOpenId());
						for (Member fan : fans) {
							if (Member.VIP_LEVEL_FANS != fan.getVipLevel()) {
								TransferMember transferMember = transferMemberService.findTransferMember(fan.getId(),
										member.getId());
								if (null == transferMember) {
									transferMemberService.executeAdd(fan.getId(), member.getId());
									logger.info("[" + member.getCardNo() + "]的粉丝[" + fan.getCardNo() + "]符合转让条件");
								}
							} else {
								Date now = Calendar.getInstance().getTime();
								BigDecimal amount = productOrderService.findTotalPayAmountinTimes(fan.getOpenId(),
										DateUtils.getBeforeOrNextDay(now, -30), now);
								if (amount.doubleValue() >= 10.00) {
									TransferMember transferMember = transferMemberService
											.findTransferMember(fan.getId(), member.getId());
									if (null == transferMember) {
										transferMemberService.executeAdd(fan.getId(), member.getId());
										logger.info("[" + member.getCardNo() + "]的粉丝[" + fan.getCardNo() + "]符合转让条件");
									}
								}
							}
						}
					}
				}
			}
		} catch (ServiceException e) {
			e.printStackTrace();
			logger.error("新增并更新可转让用户时遇到错误,错误码：" + e.getCode() + "，错误信息：" + e.getMessage(), e);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("新增并更新可转让用户时遇到错误", e);
		}
	}

	@Override
	public void offTransferMemberProduct() {
		try {
			for (int pageNo = 1; pageNo < 1000000; pageNo++) {
				List<TransferMemberProduct> transferMemberProducts = transferMemberProductService
						.findTransferMemberProducts(pageNo, 100);
				if (null == transferMemberProducts || transferMemberProducts.isEmpty()) {
					break;
				}
				for (TransferMemberProduct transferMemberProduct : transferMemberProducts) {
					int days = DateUtils.daysBetween(transferMemberProduct.getApplyTime(), new Date());
					if (days >= 30) {
						transferMemberProductService.executeOffTransferMemberProduct(transferMemberProduct);
						logger.info("transferMemberProduct[id=" + transferMemberProduct.getId() + "]上架超过30天，已自动下架");
					}
				}
			}
		} catch (ServiceException e) {
			e.printStackTrace();
			logger.error("下架超时转让时遇到错误,错误码：" + e.getCode() + "，错误信息：" + e.getMessage(), e);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("下架超时转让时遇到错误", e);
		}
	}

}
